import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/store/user'

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/harborSpace/trace',
        redirect: '/harborSpace/trace/task'
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/pages/login/index.vue'),
    },
    {
        path: '/harborSpace',
        name: 'harborSpace',
        component: () => import('@/pages/index.vue'),
        children: [
            {
                path: '',
                redirect: '/harborSpace/home'
            },
            {
                path: 'home',
                name: 'Home',
                component: () => import('@/pages/home/index.vue'),
            },
            {
                path: 'user',
                name: 'AdminUser',
                component: () => import('@/pages/user/index.vue'),
            },
            {
                path: 'trace/task',
                name: 'TraceTask',
                component: () => import('@/pages/trace/task.vue'),
            },
            {
                path: 'trace/task/:id',
                name: 'TraceTaskDetail',
                component: () => import('@/pages/trace/detail.vue'),
                props: true
            },
            {
                path: 'trace/archive',
                name: 'TraceArchive',
                component: () => import('@/pages/trace/archive.vue'),
            },
            {
                path: 'smart',
                name: 'Smart',
                component: () => import('@/pages/smart/index.vue'),
            },
            {
                path: 'user/profile',
                name: 'UserProfile',
                component: () => import('@/pages/profile/index.vue'),
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

router.beforeEach((to, from, next) => {
    const userStore = useUserStore()
    const token = userStore.token

    // 如果访问登录页，直接放行
    if (to.path === '/login') {
        return next()
    }

    // 如果访问非登录页，没有 token，则重定向到登录页
    if (!token) {
        return next('/login')
    }

    // 否则放行
    next()
})

export default router
